import React,{ useState, useMemo, useCallback } from 'react'
import { withRouter } from 'react-router-dom'
import { Button, Dropdown, Modal, Form, Input, Spin, message, Menu } from 'antd'
import { 
    MenuFoldOutlined, 
    MenuUnfoldOutlined, 
    DownOutlined,HomeOutlined, 
    BarcodeOutlined, 
    AccountBookOutlined,
    RobotOutlined,
    ClusterOutlined
} from '@ant-design/icons'
import './index.less'
import { connect } from 'react-redux'
import {CLEAR_COMMON_STATE} from '../../store/action/types'
import { updatePwdApi } from '../../apis/userApi'

const {SubMenu} = Menu

//icon图标
const MENU_ICONS ={
    'HOME-01': {icon: <HomeOutlined />},
    'PROJECT-01': {icon: <BarcodeOutlined />},
    'PURCHASE-01': {icon: <AccountBookOutlined />},
    'RECEIVING-01': {icon:<RobotOutlined />},
    'SYSTEM-01': {icon: <ClusterOutlined />},
}

//定义权限
const menuRole = {
    // "HOME-01-01": 'R',
    // "PROJECT-01-01": ['C', 'R', 'U', 'D'],
    // "PROJECT-01-02": ['C', 'U'],
    // "PURCHASE-01-01":['C', 'R', 'U', 'D', 'A'],
    // "PURCHASE-01-02":['C', 'U'],
    // "RECEIVING-01-01":['C', 'R', 'U', 'D', 'A'],
    // "RECEIVING-01-02": ['C','U'],
    // "SYSTEM-01-01":['C', 'R', 'U', 'D'],
    // "SYSTEM-01-02":['C', 'U'],
    // "SYSTEM-01-04":['C', 'R', 'U', 'D'],
    // "SYSTEM-01-05":['C', 'R', 'U', 'D'],
    // "SYSTEM-01-06":['C', 'R', 'U', 'D']

    "HOME-01-01": 'R',
    "PROJECT-01-01": 'R',
    "PROJECT-01-02": 'U',
    "PURCHASE-01-01": 'A',
    "PURCHASE-01-02": 'U',
    "RECEIVING-01-01": 'A',
    "RECEIVING-01-02": 'U',
    "SYSTEM-01-01": 'D',
    "SYSTEM-01-02":'U',
    "SYSTEM-01-04": 'R',
    "SYSTEM-01-05": 'U',
    "SYSTEM-01-06": 'D'
}

function pageLayout(Child) {
    function PageLayout({userInfo, dispatch, history, location, menuList, roleList, match}) {
        // console.log(roleList);

        const [collapsed, setCollapsed] = useState(false),
            [show,setShow] = useState(false),
            [newPassword,setNewPassword] = useState(false),
            [confirmPassword,setConfirmPassword] = useState(false),
            [loading,setLading] = useState(false),
            //因为useForm是通过useState来进行封装的，因此在使用的时候，需要使用[]来进行解构
            [myForm] = Form.useForm()
            
            // debugger

            const pageMenu = useMemo(function() {
                return menuList.filter(val => !val.parentId).map(it => {
                    it.icon =  MENU_ICONS[it.id].icon
                    it.children = menuList.filter(item => item.parentId === it.id)
                    return it
                })
            },[menuList])
            // console.log(pageMenu);

            const toPage = useCallback(function(nowMenu) {
                console.log(nowMenu);
                //页面跳转不需要权限，直接跳转
                // debugger
                // history.push(nowMenu.path)
                let pageRight = menuRole[nowMenu.id]
                if (!pageRight) {
                    history.push(nowMenu.path)
                } else {
                    let myPageRight = roleList.find(item => item.id === nowMenu.id)
                    if (!myPageRight) {
                        message.warning(`你暂时没有【${nowMenu.name}】页面访问权限`)
                    } else {
                        if (myPageRight.role.includes(pageRight)){
                            history.push(nowMenu.path)
                        } else {
                            message.warning(`你暂时没有【${nowMenu.name}】页面访问权限`)
                        }
                    }
                }
                // console.log(nowMenu, menuRole ,roleList)
            },[roleList,history])

            function handleOk() {
                // debugger
                myForm.validateFields()
                .then(async () => {
                    setLading(true)
                    let result = await updatePwdApi({id: userInfo.id, password: newPassword})
                    console.log(result);
                    // debugger
                    if(result.code === 200) {
                        message.success('修改密码成功')
                        // debugger
                        dispatch({type:CLEAR_COMMON_STATE})
                        //执行页面重定向到登陆页面
                        history.push('/login')
                    } else {
                        message.error('修改密码失败，请重试')
                    }
                    setLading(false)
                })
                .catch(function() {
                    // debugger
                    console.log('2');
                })
            }

        return (
            <>
                <div className={collapsed ? "page-layout-container coll-pase" : "page-layout-container"}>
                    <aside>
                        <span className="title">工单管理系统</span>
                        <div className="box">
                            <Menu defaultSelectedKeys={['1']}
                                defaultOpenKeys={['sub1']}
                                mode="inline"
                                theme="dark"
                                inlineCollapsed={collapsed}>
                                {
                                    !!pageMenu && pageMenu.length > 0 && 
                                    pageMenu.map(parent => {
                                        return (<SubMenu key={parent.id} icon={parent.icon} title={parent.name}>
                                            {
                                                parent.children.length > 0 && parent.children.map(children => {
                                                    return <Menu.Item onClick={toPage.bind(null, children)} key={children.id}> {children.name} </Menu.Item>
                                                })
                                            }
                                        </SubMenu>)
                                    })
                                }
                            </Menu>
                        </div>
                    </aside>
                    <main>
                        <nav>
                            <Button type="primary" icon={collapsed ? <MenuUnfoldOutlined/> : <MenuFoldOutlined />} 
                                onClick={
                                    function(){
                                        setCollapsed(!collapsed)
                                    }
                                }
                            size="middle" />
                            <span className="text">当前位置：基础系统 &gt; 用户管理</span>
                            <div className="right">
                                <Dropdown overlay={
                                        <div className="page-layout-dropdown">
                                            <span onClick={
                                                function() {
                                                    setShow(true)
                                                }
                                            }>修改密码</span>
                                            <span onClick={
                                                function(){
                                                    dispatch({type:CLEAR_COMMON_STATE})
                                                    history.push('/login')
                                                }
                                            }>退出系统</span>
                                        </div>
                                    } trigger={['click']}>
                                    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                                    Click me <DownOutlined />
                                    </a>
                                </Dropdown>
                            </div>
                        </nav>
                        <article>
                            <Child history={history} location={location} match={match}/>
                        </article>
                    </main>
                </div>
                <Modal title="Basic Modal" 
                maskClosable={false}
                visible={show} 
                onOk={handleOk} 
                onCancel={
                    function() {
                        setShow(false)
                    }
                }>
                    <Spin spinning={loading} >
                        <Form name="basic" 
                        labelCol={{ span: 8 }}
                        form={myForm }
                        wrapperCol={{ span: 16 }}
                        initialValues={{ remember: true }}>
                            <Form.Item label="新密码" 
                            name="newPassword" 
                            rules={[
                                    { required: true, message: '输入新密码'},
                                    { min: 6, type: 'string', message: '密码最小长度6个字符'},
                                    { max: 12, type: 'string', message: '密码最大长度12个字符'}
                                ]}>
                                <Input value={ newPassword } onChange={function(evt){setNewPassword(evt.target.value) }}/>
                            </Form.Item>
                            <Form.Item label="确认密码" 
                            name="confirmPassword" 
                            rules={[
                                    { required: true, message: '输入确认密码'},
                                    { min: 6, type: 'string', message: '密码最小长度6个字符'},
                                    { max: 12, type: 'string', message: '密码最大长度12个字符'},
                                    {
                                        validator: (_, value ) => {
                                            //return value ? Promise.reject(new Error('should accept agreement'))
                                            if (value !== newPassword) {
                                                return Promise.reject(new Error('确认密码和新密码不一致'))
                                            } else {
                                                return Promise.resolve()
                                            }
                                        }
                                    }
                                ]}>
                                <Input value={ confirmPassword } onChange={ function(evt){setConfirmPassword(evt.target.value) }}/>
                            </Form.Item>
                        </Form>
                    </Spin>
                </Modal>
            </>
        ) 
    }
    //一定要注意，这里的pageLayout是一个高价组件的方法，而PageLayout才是组件，因此connect高阶方法因该作用于PageLayout
    return connect(function(state) {
        return {
            userInfo: state.common.userInfo,
            menuList: state.common.menuList,
            roleList: state.common.roleList
        }
    })(withRouter(PageLayout))
}

export default pageLayout